<link href="/lib/woofmark/dist/woofmark.min.css" rel="stylesheet">
<link href="/lib/bootstrap-tokenfield/dist/css/tokenfield-typeahead.min.css" rel="stylesheet">
<link href="/lib/bootstrap-tokenfield/dist/css/bootstrap-tokenfield.min.css" rel="stylesheet">

<!-- required for TagsModule -->
<script src="/lib/typeahead.js/dist/bloodhound.js"></script>
<script src="/lib/bootstrap-tokenfield/dist/bootstrap-tokenfield.js"></script>

<!-- required for MainImageModule -->
<script src="/lib/jquery-file-upload/js/vendor/jquery.ui.widget.js"></script>
<script src="/lib/jquery-file-upload/js/jquery.iframe-transport.js"></script>
<script src="/lib/jquery-file-upload/js/jquery.fileupload.js"></script>

<link href="/lib/publiclab-editor/dist/PublicLab.Editor.css" rel="stylesheet">

<script src="/lib/publiclab-editor/dist/PublicLab.Editor.js"></script>

<% if params[:action] == "new" && params[:controller] == "wiki" && feature('new-wiki-modal') %>
  <div class="container">
    <div class="modal fade" id="newWikiTemplateChooser" tabindex="-1" role="dialog" aria-labelledby="Wiki templates" aria-hidden="true">
      <div class="modal-dialog" role="document">
        <%= feature('new-wiki-modal') %>
      </div>
    </div>
  </div>
  <script>
  $(window).on('load',function(){
    $('#newWikiTemplateChooser').modal('show');
  });
  </script>
<% end %>

<div class="pl-editor">

  <div class="ple-header">

    <h1><%= raw translation('editor.wikiRich.new_wiki') %></h1>

  </div>

  <div class="ple-content">

    <!-- title module -->
    <div class="ple-module-title ple-module container">

      <div class="ple-module-guide col-md-3">
        <h2>1</h2>
      </div>

      <div class="ple-module-content col-md-9">
        <input class="form-control input-lg" type="text" placeholder="Title" value="<%= if @node then @node.title else params[:title] end %>" />
      </div>

    </div>
    <!-- end title module -->


    <!-- main_image module -->
    <div class="ple-module-main_image ple-module container">

      <div class="ple-module-guide col-md-3">
        <h2>2</h2>
      </div>

      <div class="ple-module-content col-md-9 container">
        <div class="ple-drag-drop col-md-6">
          Drag an image here to upload.
        </div>
        <div class="col-md-6 help">

          <div style="display:none;" class="progress">
            <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>
          </div>

          <p><input type="file"  accept=".png, .jpg, .jpeg" name="image[photo]" value="<% if @node && @node.main_image(:rails) %><%= @node.main_image(:rails).id %><% else %><%= params[:main_image] %><% end %>" /></p>
          <p class="ple-help"><span class="ple-help-minor">Select an optional main image for your post.</span></p>

        </div>
      </div>

    </div>
    <!-- end main_image module -->


    <!-- body module -->
    <div class="ple-module-body ple-module container">

      <div class="ple-module-guide col-md-3">
        <h2>3</h2>
      </div>

      <div class="ple-module-content col-md-9 container">
        <textarea id="text-input" class="ple-textarea form-control"><% if @node && @node.latest && @node.latest.body_rich %><%= @node.latest.body %><% else %><%= params[:body] %><% end %></textarea>
      </div>

    </div>
    <!-- end body module -->


    <!-- tags module -->
    <div class="ple-module-tags ple-module container">

      <div class="ple-module-guide col-md-3">
        <h2>4</h2>
      </div>

      <div class="ple-module-content col-md-9">
        <input class="form-control input-lg" type="text" placeholder="balloon-mapping, water-quality..." value="<% if params[:tags] || (@node && @node.tagnames) %><%= params[:tags] || @node.tagnames.join(',') %><% end %>" />
      </div>

    </div>
    <!-- end tags module -->

  </div>

  <div class="ple-footer">

    <div class="ple-menu-more" style="display:none;">
      <b>History</b>
      <div class="ple-history">
      </div>
      <hr />
      <!--
      <div class="form-control input-md ple-history">
        <option selected value="">recent edits</option>
      </div>
      -->
    </div>

    <button class="btn btn-lg btn-default btn-more">...</button>

    <span> &nbsp; By publishing, you agree to <a href="https://publiclab.org/licenses">open source your work</a><span class="hidden-xs"> so that others may use it.</span></span>

    <button class="ple-publish btn btn-lg btn-primary pull-right disabled">Publish</button>
    <span class="ple-help pull-right">
      <span class="ple-steps-left">2</span>
      <span class="hidden-xs"> steps left</span>
    </span>

  </div>

</div>


<script>
  var editor;
  (function() {
    editor = new PL.Editor({
      data: {
        token: $('meta[name="csrf-token"]').attr('content')
      },
      textarea:    $('.ple-textarea')[0],
      <% if @main_image %>
        mainImageUrl:   '<%= @main_image %>',
      <% end %>
      <% if params[:action] == 'edit' %>
        destination: '/notes/update/<%= @node.id %>?rich=true',
      <% else %>
        destination: '/notes/create?rich=true',
      <% end %>
      <% if params[:redirect] == 'question' %>
        redirect: 'redirect',
      <% end %>
      <% if (@node && @node.errors.size > 0) && (@revision && @revision.errors.size > 0) %>
        errors: <%=raw (@node.errors.to_h.merge(@revision.errors.to_h)).to_json %>,
      <% elsif (@node && @node.errors.size > 0) %>
        errors: <%=raw (@node.errors.to_h).to_json %>,
      <% elsif (@revision && @revision.errors.size > 0) %>
        errors: <%=raw (@revision.errors.to_h).to_json %>,
      <% end %>
      format:      'publiclab',
      publishCallback: function publishCallback(response) {
        // parse and display errors!
        if (typeof response === "string") {
          if (response.substr(1, 8) == "!DOCTYPE") $('.ple-errors').html('<div class="alert alert-danger">There was an error posting. Please contact web@publiclab.org for assistance - and note that your draft is saved under the "..." menu at the lower left.</div>');
          else window.location = response;
        } else if (response && Object.keys(response).length > 0) {
          $('.ple-errors').html('<div class="alert alert-danger"></div>');
          Object.keys(response).forEach(function(key, i) {
            $('.ple-errors .alert').append('<p><b>' + key + '</b> </p>');
            $('.ple-errors .alert p:last').append(response[key].join(', '));
          });
          window.scroll(0, 0);
        }
      },
      mainImageModule: {
        uid: <%= current_user.id %><% if @node && @node.id %>,
	nid: <%= @node.id %><% end %>,
        token: $('meta[name="csrf-token"]').attr('content')
      },
      richTextModule: {
        authorsAutocomplete: false,
        tagsAutocomplete: false,
        formats: ['csv', 'xls', 'zip', 'kml', 'kmz', 'gpx', 'lut', 'stl', 'dxf', 'txt', 'pdf', 'svg', 'doc', 'ppt', 'docx', 'bmp', 'obj', 'json', 'jpg', 'jpeg', 'png', 'gif']
      },
      titleModule: {
        suggestRelated: true,
        fetchRelated: debounce(function(show) {
          $.getJSON("/api/srch/notes?query=" + editor.titleModule.value(), function(response) {
            /* API provides:
            {"items":[{
              "doc_id":14022,
              "doc_type":"file",
              "doc_url":"/notes/liz/03-15-2017/host-a-balloon-mapping-workshop",
              "doc_title":"Host a balloon mapping workshop",
              "doc_score":0}
            ]}
            */
            // But we need: [{ id: 1, title: 'A related post',       url: '/', author: 'eustatic'}, ... ]
            var formatted = [];
            if (response['items']) {
              response['items'].forEach(function(item) {
                var formattedItem = {};
                formattedItem.id = item.doc_id;
                formattedItem.title = item.doc_title;
                formattedItem.url = item.doc_url;
                formattedItem.author = item.doc_url.split('/')[2];
                formatted.push(formattedItem);
              });
              show(formatted);
            }
          });
        }, 1000)
      },
      tagsModule: {
        remote: {
          url: "/tag/suggested/test",
          prepare: function prepareRemote(x) {
            return "/tag/suggested/" + x
          }
        }
      }
    });
  })();
  $('.legacy-button').click(function onLegacyClick(event) {
      event.preventDefault();
      window.location = "/wiki/new?legacy-true&body=" + editor.richTextModule.value() + "&tags=" + editor.tagsModule.value() + "&title=" + editor.titleModule.value();
    });
</script>
